import moment from 'moment'
import html2canvas from "./html2canvas.esm.js";
import { Message } from 'element-ui'
// import { qrcanvas } from "qrcanvas";//生成二维码(没安装，需要自行安装cnpm i -S qrcanvas )
//转import default from './OnlyDialog';
//换时间
export function transformation(data) {//传入时间戳转成文字形式
    let result = ''
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var year = month * 12
    let timeStamp = new Date().getTime()
    var diffValue = timeStamp - data ;//是否要*1000
    if (diffValue < 0) {
        return;
    }
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var yearC = diffValue / year;
    if (yearC >= 1) {
        result = "" + parseInt(yearC) + "年前";
    } else if (monthC >= 1) {
        result = "" + parseInt(monthC) + "月前";
    } else if (weekC >= 1) {
        result = "" + parseInt(weekC) + "周前";
    } else if (dayC >= 1) {
        result = "" + parseInt(dayC) + "天前";
    } else if (hourC >= 1) {
        result = "" + parseInt(hourC) + "小时前";
    } else {
        result = "刚刚";
    }
    return result;
}
export function phoneNumFilter(phone) {//将手机号转成 173****1400 的形式
    // 1字符串转化成数组
    let phoneArr = [...phone];
    let str = ''
    // 2.将数组中的4-7位变成*
    phoneArr.map((res, index) => {
        if (index > 2 && index < 7) {
            str += '*';
            // return '*';
        } else {
            str += res;
            // return res;
        }
    });
    console.log(str);
    return str;
}
export function cardFilter(num) {//将银行卡号转成 ****  ****  **** 00000 的形式
        return '****  ****  ****  ' + num.substring(num.length - 4);
}
export function addDays(date,days) {//date(年月日时间或者时间戳) days(需要增加的天数) [添加]
    return moment(date).add(days, "day").format('YYYY-MM-DD');
}
export function addMonths(date,months) {//date(年月日时间或者时间戳) months(需要增加的月数) [添加]
    return moment(date).add(months, "months").format('YYYY-MM-DD');
}
export function addYear(date,year) {//date(年月日时间或者时间戳) year(需要增加的年数) [添加]
    return moment(date).add(year, "year").format('YYYY-MM-DD');
}
export function subtractDays(date,days) {//date(年月日时间或者时间戳) days(需要增加的天数) [减少]
    return moment(date).subtract(days, "day").format('YYYY-MM-DD');
}
export function subtractMonths(date,months) {//date(年月日时间或者时间戳) months(需要增加的月数) [减少]
    return moment(date).subtract(months, "months").format('YYYY-MM-DD');
}
export function subtractYear(date,year) {//date(年月日时间或者时间戳) year(需要增加的年数) [减少]
    return moment(date).subtract(year, "year").format('YYYY-MM-DD');
}
export function objectMatching(obj,obj1){//对象与对象相同赋值
    for(let i in obj){
      for(let j in obj1){
          if(i==j){
           obj1[j]=obj[i]
          }
      }
    }
    return obj1
}
export function qrCode(id,imgUrl,url,size){//生成二维码
    let img = new Image();
            img.src =imgUrl;//二维码中间图片url
            img.onload = function() {
                const canvas = qrcanvas({
                    data: url,//产生二维码的url
                    size: size?size:'300',
                    logo: {
                        image: img,
                    },
                });
                // @ts-ignore;
                document.getElementById(id).appendChild(canvas);
            };
}
export function generatePicture(ref,name){//用div生成图片并下载下来
    html2canvas(ref, {
        // //允许图片跨域
        // useCORS: true,
        // taintTest: false,
        // logging: true, 
        // //背景颜色
        // backgroundColor: color,
        // // 如果需要合成的数据超过页面-出现滚动条，需要打开这些
        // // width: window.screen.availWidth,//显示窗口canvas的宽度
        // // windowWhidth: document.body.scrollWidth,//获取x方向滚动条内容
        // // windowHeight: $("#box").get(0).offsetHeight,//获取y方向滚动条内容
        // // x: 0,//页面滚动
        // // y: window.pageYOffset////页面滚动
    }).then(canvas => {
        const link = document.createElement("a");
        link.href = canvas.toDataURL();
        link.setAttribute("download",name?name:moment(new Date()).format('YYYY-MM-DD') + ".png");
        link.style.display = "none" + document.body.appendChild(link);
        link.click();
    }).catch(()=>{
        Message.error("生成图片失败，请重新生成!")
    })
}
export function copy(object) {//实现数据深拷贝问题
    // 判断传入的参数是数组还是对象
    // let target = object instanceof Array ? [] : {}
    // for (const [k ,v] of Object.entries(object)) {
    //   target[k] = typeof v == 'object' ? copy(v) : v
    // }
    let target=JSON.parse(JSON.stringify(object))
    return target
  }
  export function randomNum(min,max){//取2个数之间的随机数
    return Math.floor(Math.random() * (max - min + 1) + min)
  }
  export function randomColor(){//获取随机颜色
    let r = parseInt(Math.random() * 256)
    let g = parseInt(Math.random() * 256)
    let b = parseInt(Math.random() * 256)
    let bgColor=`rgba(${r},${g},${b},0.3)`
    return  bgColor
  }

 export function loop(data,bool){//树形组件全部设置为禁用或者开启
   
     data.map(item=>{
           item.disabled=bool
        if(item.children){
            G(item.children,bool)
        }
        return item
     })
     console.log(data);
    return data
 }
 function G(data,bool){
    data.map(item=>{
        item.disabled=bool
     if(item.children){
         G(item.children,bool)
     }
     return item
  })
 }
 export function transferData(data,son,father){
    var r = [];
    var tmpMap = {};
    for (var i = 0, l = data.length; i < l; i++) {
      // 以每条数据的id作为obj的key值，数据作为value值存入到一个临时对象里面
      tmpMap[data[i][father]] = data[i];
    }
    // console.log("tmpMap", tmpMap);
    for (i = 0, l = data.length; i < l; i++) {
      var key = tmpMap[data[i][son]];
      // console.log("key", key);
      //循环每一条数据的 fid，假如这个临时对象有这个key值，就代表这个key对应的数据有children，需要Push进去
      //如果这一项数据属于哪个数据的子级
      if (key) {
        // 如果这个数据没有children
        if (!key["children"]) {
          key["children"] = [];
          key["children"].push(data[i]);
          // 如果这个数据有children
        } else {
          key["children"].push(data[i]);
        }
      } else {
        //如果没有这个Key值，就代表找不到属于哪个数据，那就代表没有父级,直接放在最外层
        r.push(data[i]);
      }
    }
    return r;
 }
 export function derivation(data,name){//后端给出文件流，前端导出
     let title=name
     if(!title){
        title=  parseInt(new Date().getTime() / 1000);
     }
    const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
    // for IE
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
     const fileName = title + '.xlsx'
     window.navigator.msSaveOrOpenBlob(blob, fileName)
    } else {
     // for Non-IE (chrome, firefox etc.)
     const fileName = title + '.xlsx'
     const elink = document.createElement('a')
     elink.download = fileName
     elink.style.display = 'none'
     elink.href = URL.createObjectURL(blob)
     document.body.appendChild(elink)
     elink.click()
     URL.revokeObjectURL(elink.href)
     document.body.removeChild(elink)
    }
   
 }


  
  
  
  